package com.spring.demo.webflux.demo.filter;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * WebFlux框架提供两种类型的过滤器：WebFilters和HandlerFilterFunctions。
 * 它们之间的主要区别是WebFilter实现可用于所有端点，而HandlerFilterFunction实现仅适用于基于路由器的实现。
 * @author wangzhilong
 * @date 2020/7/15
 */
@Component
//数字越小的排在前面
@Order(0)
public class AuthFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        final ServerHttpRequest request = exchange.getRequest();
        final ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().value();
        if (path.contains("push") || path.contains("sse") || path.contains("htm")) {
            return chain.filter(exchange);
        }
        final String token = request.getHeaders().getFirst("token");
        if (null == token) {
            //直接返回响应结果，跳过后面的filter和controller
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"no token\"}".getBytes())));
        } else if (StringUtils.pathEquals("110", token)) {
            // 修改请求的目标url为/auth/error
            // request.mutate返回一个请求构建器(builder design pattern)，path方法修改请求的url，build方法返回新的request
            // 最后调用chain.filter将请求forward到修改后的url：/auth/error
            final ServerHttpRequest authErrorReq = request.mutate().path("/auth/error").build();
            final ServerWebExchange authErrorExchange = exchange.mutate().request(authErrorReq).build();
            return chain.filter(authErrorExchange);
        } else {
            return chain.filter(exchange);
        }
    }
}
